import router from './router'
import store from './store'
import { Message } from 'element-ui'
// 引入进度条工具库
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 白名单
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

/**
 * 路由的全局前置守卫
 */
router.beforeEach(async(to, from, next) => {
  // start progress bar
  // 开启进度条
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  // 判断是否有token
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      // 拦截去主页面
      next({ path: '/' })
      // 手动强制关闭一次
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      //console.log('hasRoles',hasRoles)
      if (hasRoles) {
        next()
      } else {
        try {
          // 处理登录用户信息
          const roles = await store.dispatch('user/getInfo')
          //处理权限
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // console.log('权限',accessRoutes)
          // router.addRoutes(accessRoutes)
          router.addRoutes([])
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else { //没有
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { //在
      // in the free login whitelist, go directly
      next()
    } else { //不在
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      // 手动强制关闭一次
      NProgress.done()
    }
  }
})

/**
 * 路由的全局后置守卫
 */
router.afterEach(() => {
  // finish progress bar
  // 关闭进度条
  NProgress.done()
})
